package com.kws.merchant.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kws.common.config.constant.MinioCommonBucket;
import com.kws.common.core.exception.ServiceException;
import com.kws.common.security.auth.AuthUtil;
import com.kws.common.security.utils.SecurityUtils;
import com.kws.merchant.domain.*;
import com.kws.merchant.domain.po.CreateContractPo;
import com.kws.merchant.domain.po.QuotationPo;
import com.kws.merchant.domain.po.SchemeVo;
import com.kws.merchant.domain.po.ServiceProviderPo;
import com.kws.merchant.domain.vo.AcceptOfferVo;
import com.kws.merchant.domain.vo.QuotationVo;
import com.kws.merchant.mapper.OnlineInquiryMapper;
import com.kws.merchant.service.*;
import com.kws.merchant.util.RedisLockService;
import com.kws.system.api.domain.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;

/**
 * @author : zhangbenting
 * @date : 2024/11/12 14:11
 * @Version: 1.0
 */
@Service
public class OnlineInquiryServiceImpl extends ServiceImpl<OnlineInquiryMapper, OnlineInquiryEntity>
        implements OnlineInquiryService {

    @Autowired
    @Lazy
    private MerchantService merchantService;

    @Autowired
    private ItemSchemeMerchantService itemSchemeMerchantService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private RedisLockService redisLockService;

    @Autowired
    private ItemUserSchemeService itemUserSchemeService;

    @Value("${minio.ENDPOINT}")
    private String minioUrl;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ContractService contractService;


//    @Override
//    @Transactional(rollbackFor = Exception.class)
//    public SchemeVo getScheme(OnlineInquiryEntity onlineInquiryEntity) {
//
//        //调取测算接口
//
//        this.save(onlineInquiryEntity);
//        //生成测算方案
//
//        //存储测算方案
//        ItemUserSchemeEntity itemUserSchemeEntity = new ItemUserSchemeEntity();
//        itemUserSchemeEntity.setSchemeId(onlineInquiryEntity.getId());
//        itemUserSchemeEntity.setSchemeName("方案名称");
//        itemUserSchemeEntity.setSchemeFile("方案文件");
//        itemUserSchemeEntity.setUserId(SecurityUtils.getUserId());
//        itemUserSchemeService.save(itemUserSchemeEntity);
//
//        SchemeVo schemeVo = new SchemeVo();
//        schemeVo.setSchemeId(itemUserSchemeEntity.getSchemeId());
//        schemeVo.setSchemeName(itemUserSchemeEntity.getSchemeName());
//        schemeVo.setSchemeInfo(minioUrl + "/" + MinioCommonBucket.HUATAI_PUB_BUCKET + "/"+itemUserSchemeEntity.getSchemeFile());
//        return schemeVo;
//    }

    @Override
    public Page<QuotationVo> getServiceProviderList(ServiceProviderPo serviceProviderPo) {
        LambdaQueryWrapper<Merchant> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(Merchant::getUserRole, serviceProviderPo.getMerchantType());
        Page<Merchant> merchantPage = new Page<>(serviceProviderPo.getPageSize(), serviceProviderPo.getTotalPage());
        Page<Merchant> merchantPageData = merchantService.page(merchantPage, wrapper);
        List<Merchant> merchantList = merchantPageData.getRecords();
        List<QuotationVo> quotationVos = new ArrayList<>();
        Page<QuotationVo> quotationVoPage = new Page<>();
        if (ObjectUtils.isNotEmpty(merchantList)) {
            for (Merchant merchant : merchantList) {
                QuotationVo quotationVo = new QuotationVo();
                quotationVo.setMerchantId(merchant.getId());
                quotationVo.setMerchantName(merchant.getCompanyName());
                quotationVos.add(quotationVo);
            }
            quotationVoPage.setRecords(quotationVos);
            quotationVoPage.setTotal(merchantPageData.getTotal());
            quotationVoPage.setPages(merchantPageData.getPages());
            quotationVoPage.setCurrent(serviceProviderPo.getPageSize());
            return quotationVoPage;
        }
        return quotationVoPage;
    }

//    @Override
//    public List<QuotationVo> getMerchantQuotation(QuotationPo quotationPo) {
//        if (ObjectUtils.isEmpty(quotationPo.getSchemeId())) {
//            return new ArrayList<QuotationVo>();
//        }
//        return baseMapper.getMerchantQuotation(quotationPo.getSchemeId());
//    }

    @Override
    @Transactional
    public boolean quotationMake(QuotationPo quotationPo) {
        SysUser sysUser = AuthUtil.getLoginUser().getSysUser();
        Long userId = sysUser.getUserId();
        List<Long> merchantIds = quotationPo.getMerchantIds();
        if (ObjectUtils.isEmpty(merchantIds)) throw new RuntimeException("请选择服务商");
        if (ObjectUtils.isEmpty(quotationPo.getSchemeId())) throw new RuntimeException("请选择方案");
        List<ItemSchemeMerchant> itemSchemeMerchants = new ArrayList<>();
        ItemUserSchemeEntity itemUserSchemeEntity = itemUserSchemeService.getOne(Wrappers.<ItemUserSchemeEntity>lambdaQuery()
                .eq(ItemUserSchemeEntity::getSchemeId, quotationPo.getSchemeId()));
        itemUserSchemeEntity.setStationId(quotationPo.getStationId());
        itemUserSchemeEntity.setStationType(quotationPo.getStationType());
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date deadlineTime = null;
        try {
            deadlineTime = dateFormat.parse(quotationPo.getReportEndTime());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        itemUserSchemeEntity.setDeadlineTime(deadlineTime);
        itemUserSchemeService.saveOrUpdate(itemUserSchemeEntity);
        for (Long merchantId : merchantIds) {
            ItemSchemeMerchant itemSchemeMerchant = new ItemSchemeMerchant();
            itemSchemeMerchant.setMerchantId(merchantId);
            itemSchemeMerchant.setStatus(1);
            itemSchemeMerchant.setSchemeId(quotationPo.getSchemeId());
            itemSchemeMerchant.setUserId(userId);
            itemSchemeMerchants.add(itemSchemeMerchant);
        }
        return itemSchemeMerchantService.saveBatch(itemSchemeMerchants);
    }

    @Override
    @Transactional
    public boolean acceptOffer(Long quotationId) {
        SysUser sysUser = AuthUtil.getLoginUser().getSysUser();
        Long userId = sysUser.getUserId();
        //生成订单
        ItemSchemeMerchant itemSchemeMerchant = itemSchemeMerchantService.getOne(Wrappers.<ItemSchemeMerchant>lambdaQuery().eq(ItemSchemeMerchant::getId, quotationId));

        AcceptOfferVo acceptOfferVo = baseMapper.acceptOffer(itemSchemeMerchant.getId());
        if (ObjectUtils.isEmpty(acceptOfferVo)) throw new ServiceException("方案不存在");
        Order order = new Order();
        long orderId = IdWorker.getId();
        String lockKey = "order_lock:" + orderId;
        String lockValue = userId.toString();
        try {
            if (!redisLockService.acquireLock(lockKey, lockValue, 5000)) {
                throw new ServiceException("获取锁失败！");
            }
            order.setId(orderId);
            order.setUserId(userId);
            order.setType(1);
            order.setOrderNo("FW" + orderId);
            order.setEnable("1");
            order.setGoodsName(acceptOfferVo.getSchemeName());
            order.setOrderPrice(acceptOfferVo.getPrice());
            order.setMerchantId(acceptOfferVo.getMerchantId());
            order.setMerchantName(acceptOfferVo.getMerchantName());
            order.setItemId(Long.valueOf(acceptOfferVo.getStationId()));
            order.setProjectType(acceptOfferVo.getStationType());
            order.setStatus(0);
            order.setIsEvaluate(0);
            order.setSchemeId(acceptOfferVo.getSchemeId());
            //生成合同
            CreateContractPo createContractPo = new CreateContractPo();
            createContractPo.setOrderId(orderId);
            if (orderService.save(order)) {
                createContractPo.setProjectType(acceptOfferVo.getStationType());
                contractService.createContract(createContractPo);
                redisTemplate.opsForValue().set("order:" + orderId, String.valueOf(orderId), 15, TimeUnit.SECONDS);
            }
        } catch (Exception e) {
            // 异常处理：记录日志并抛出异常
            throw new RuntimeException("下单失败：" + e.getMessage());
        } finally {
            // 释放锁
            redisLockService.releaseLock(lockKey, lockValue);
        }
        itemSchemeMerchant.setStatus(2);
        return itemSchemeMerchantService.saveOrUpdate(itemSchemeMerchant);
    }

}
